package kr.hkit.summury_java.erp.garbage;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import kr.hkit.myframework.uicomp.InputPanel;
import kr.hkit.summury_java.erp.dao.DaoInterface;
import kr.hkit.summury_java.erp.dto.Department;

public class PanelDepartmentUpdateUI extends JPanel implements ActionListener {
	private InputPanel pDeptno;
	private InputPanel pDeptName;
	private InputPanel pFloor;
	private JPanel panel_top;
	private JPanel panel_bottom;
	private JButton btnUpdate;
	
	private DaoInterface<Department> dao;

	/**
	 * Create the panel.
	 */
	public PanelDepartmentUpdateUI() {

		initialize();
	}
	
	public void setDao(DaoInterface<Department> dao) {
		this.dao = dao;
	}

	private void initialize() {
		setLayout(new BorderLayout(0, 0));
		
		panel_top = new JPanel();
		add(panel_top);
		panel_top.setLayout(new GridLayout(0, 1, 0, 30));
		
		pDeptno = new InputPanel("부서번호");
		panel_top.add(pDeptno);
		
		pDeptName = new InputPanel("부서명");
		panel_top.add(pDeptName);
		
		pFloor = new InputPanel("위치");
		panel_top.add(pFloor);
		
		panel_bottom = new JPanel();
		add(panel_bottom, BorderLayout.SOUTH);
		
		btnUpdate = new JButton("수정");
		btnUpdate.addActionListener(this);
		panel_bottom.add(btnUpdate);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnUpdate) {
			actionPerformedBtnAdd(e);
		}
	}
	
	private boolean inValidCheck() {
		//공백만 체크
		if(pDeptno.getTf().getText().equals("")) {
			pDeptno.getTf().requestFocus();
			return false;
		}
		if(pDeptName.getTf().getText().equals("")) {
			pDeptName.getTf().requestFocus();
			return false;
		}
		return true;
	}
	
	private Department getInfo() {
		if (inValidCheck()){
			int dno = Integer.parseInt(pDeptno.getTf().getText().trim());
			String name = pDeptName.getTf().getText();
			int floor = Integer.parseInt(pFloor.getTf().getText().trim());	
			
			return new Department(dno, name, floor);
		} else {
			return null;
		}
	}
	
	private void setIniTf() { //텍스트필드 초기화
		pDeptno.getTf().setText("");
		pDeptName.getTf().setText("");
		pFloor.getTf().setText("");
	}
	
	protected void actionPerformedBtnAdd(ActionEvent e) {
		try {	
			Department d = getInfo();
			dao.updateItemByNo(d);
			JOptionPane.showMessageDialog(this, "정상적으로 수정되었습니다.");
			setIniTf();
			
		} catch (SQLException e1) {
			JOptionPane.showMessageDialog(this, "입력을 실패하였습니다. 다시 확인하여 주세요.");
		} catch (NumberFormatException e2) {
			JOptionPane.showMessageDialog(this, "정보를 입력해주세요.");
		}
	}
}
